import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/Home/MyHome.vue'


const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/login',
    name: 'login',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Login/MyLogin.vue')
  },
  {
    path: '/detail',
    name: 'detail',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Detail/MyDetail.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/cart',
    name: 'cart',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Cart/MyCart.vue'),

    meta: { requiresAuth: true } 

  },
  {
    path: '/order',
    name: 'order',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Order/MyOrder.vue'),
    
    // meta: { requiresAuth: true } 

  },
  {
    path: '/guanyu',
    name: 'guanyu',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Guanyu/GuanYu.vue'),
    
    // meta: { requiresAuth: true } 

  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})


router.beforeEach((to, from, next) => {
    const token = sessionStorage.getItem('token');
    const isProtected = to.meta.requiresAuth;
  
    if (isProtected) {
      if (token) {
        next();
      } else {
        sessionStorage.setItem('redirectAfterLogin', to.fullPath);
        next('/login');
      }
    } else {
       next();
    }
  });
  


export default router
